<script lang="ts" setup>
import { ref, onMounted, computed, onBeforeMount } from "vue";

const xMove = ref<number>(0);
const yMove = ref<number>(0);

const xMovePx = computed(() => `${xMove.value}px`);
const yMovePx = computed(() => `${yMove.value}px`);
let moveSpeed = ref(10);
const keyWordObj = computed<any>(() => {
  return {
    w: -moveSpeed.value,
    s: moveSpeed.value,
    a: -moveSpeed.value,
    d: moveSpeed.value,
  };
});
const speed = ref<any>(null);
const box = ref<any>(null);

const container = ref<any>(null);
const containerLfet = ref(0);
const containerTop = ref(0);
const containerBottom = ref(0);
const containerRight = ref(0);

const showSeepdBox = ref(true);

const speedLfet = ref(0);
const speedTop = ref(0);
const speedBottom = ref(0);
const speedRight = ref(0);
const handleKey = (e: any) => {
  const { top, left, bottom, right } = box.value.getBoundingClientRect();
  if (
    (e.key == "w" && top <= containerTop.value + 10) ||
    (e.key == "a" && left <= containerLfet.value + 10) ||
    (e.key == "s" && bottom >= containerBottom.value - 10) ||
    (e.key == "d" && right >= containerRight.value - 10)
  ) {
    return;
  }
  if (e.key == "a" || e.key == "d") {
    xMove.value += keyWordObj.value[e.key];
  }
  if (e.key == "w" || e.key == "s") {
    yMove.value += keyWordObj.value[e.key];
  }

  if (
    top >= speedTop.value &&
    left >= speedLfet.value &&
    bottom <= speedBottom.value &&
    right <= speedRight.value
  ) {
    showSeepdBox.value = false;
    moveSpeed.value = 50;
  }
};

onMounted(() => {
  window.addEventListener("keydown", handleKey);

  const { top, left, bottom, right } = speed.value.getBoundingClientRect();
  speedLfet.value = left - 50;
  speedTop.value = top - 50;
  speedBottom.value = bottom + 50;
  speedRight.value = right + 50;

  const containerBox = container.value.getBoundingClientRect();
  containerLfet.value = containerBox.left;
  containerTop.value = containerBox.top;
  containerBottom.value = containerBox.bottom;
  containerRight.value = containerBox.right;
});
onBeforeMount(() => {
  window.removeEventListener("keydown", handleKey);
});
</script>

<template>
  <div ref="container" class="border-1 w-500px h-500px m-auto">
    <div ref="box" class="bg-red-500/50 w-50px h-50px move"></div>
    <div
      v-if="showSeepdBox"
      ref="speed"
      class="bg-blue-500/50 w-50px h-50px m-auto text-[#fff]"
    >
      加速
    </div>
  </div>
</template>

<style lang="less" scoped>
.move {
  transform: translate(v-bind(xMovePx), v-bind(yMovePx));
  transition: all 0.1s;
}
</style>
